<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElMessageBox } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import Edit from './components/Edit.vue'
import See from './components/See.vue'

import { Table } from '@/components/Table'

import { adminFaPastureListApi } from '@/api/fa/pasture'

import { useTable } from '@/hooks/web/useTableTest'
import { ref, reactive, unref } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')

const iconEdit = useIcon({ icon: 'ep:edit' })
const iconSee = useIcon({ icon: 'ep:view' })
const iconDel = useIcon({ icon: 'ep:delete' })
const iconFile = useIcon({ icon: 'material-symbols:drive-file-move-sharp' })
const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: adminFaPastureListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

getList()

const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

// const datas = reactive({
//   name: [required],
//   percentage: [required],
//   breed: [required],
//   breed_sub: [required],
//   state: [required]
// })
const datas: any = [
  {
    id: 1,
    name: '设备1',
    unit: '只',
    stock: 0,
    creation_time: '2022-12-13 20:30:00',
    state: 1
  },
  {
    id: 2,
    name: '设备2',
    unit: '只',
    stock: 2000,
    creation_time: '2023-12-13 19:12:00',
    state: 2
  }
]
console.log(datas, 'iii')
// console.log(tableObject, 'tableObject')
// console.log(tableObject, 'tableObject')

const { t } = useI18n()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'name',
    label: '设备名称',
    search: {
      show: true
    }
  },
  {
    field: 'unit',
    label: '设备单位',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('unit', cellValue)
    },
    form: {
      component: 'Select',
      componentProps: {
        options: dict.unit
      }
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.unit
      },
      show: true
    }
  },
  {
    field: 'stock',
    label: '库存',
    search: {
      show: true
    },
    form: {
      show: false
    }
  },
  {
    field: 'creation_time',
    label: '创建时间',
    width: 170,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    form: {
      show: false
    }
  },
  {
    field: 'action',
    width: 200,
    fixed: 'right',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      // tableObject.currentRow = {
      //   is_stop: '0'
      // }
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm(`删除该设备档案？`, '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 归档
          del()
        })
        .catch(() => {
          console.log('这里是删除设备档案')
        })
      break
    case 'file':
      ElMessageBox.confirm(`归档后不可以修改删除，是否归档？`, '归档', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 归档
          file()
          // deleteApi(data.knowledge_class_id)
        })
        .catch(() => {
          console.log('这里是取消归档')
        })
      break
    default:
      console.log('未知类型')
  }
}
const del = () => {
  console.log('删除', 'bbb')
}
const file = () => {
  console.log('归档', 'aaa')
}
const editRef = ref<ComponentRef<typeof Edit>>()
const loading = ref(false)
const save = async () => {
  const edit = unref(editRef)
  switch (actionType.value) {
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as any
          // console.log(3333, data, adminFaPastureEditApi)
          let res = await adminFaPastureEditApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    case 'add':
      await edit?.elFormRef?.validate(async (isValid) => {
        console.log(edit?.elFormRef, 'edit?.elFormRef')
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as any
          // const datas = (await edit?.tableDatas) as any
          console.log(data, 'data')
          // console.log(datas, 'datas')
          // const a = true
          // datas.some((element) => {
          //   if (element.feed == undefined || element.percentage == undefined) {
          //     return ElMessageBox.confirm('设备档案信息未填写完整', '提示', {
          //       confirmButtonText: '确认',
          //       cancelButtonText: '取消',
          //       type: 'warning'
          //     })
          //       .then(() => {
          //         // deleteApi(data.id)
          //         a = false
          //         loading.value = false
          //       })
          //       .catch(() => {
          //         a = false
          //         loading.value = false
          //       })
          //   }
          // })
          // if (a == true) {
          //   const params = { ...data, ...datas }
          //   console.log(params, 'params')
          //   console.log(datas, 'datas')
          //   let sum = 0
          //   for (var i = 0; i < datas.length; i++) {
          //     sum += Number(datas[i].percentage)
          //   }
          //   if (sum != 100) {
          //     ElMessageBox.confirm('设备档案配比不正确，请修改后提交', '提示', {
          //       confirmButtonText: '确认',
          //       cancelButtonText: '取消',
          //       type: 'warning'
          //     })
          //       .then(() => {})
          //       .catch(() => {})
          //   }
          // }
          // let res = await adminFaPastureEditApi(data)
          //   .catch(() => {})
          //   .finally(() => {
          //     loading.value = false
          //   })
          // if (res) {
          //   dialogVisible.value = false
          //   tableObject.currentPage = 1
          //   getList()
          // }
        }
      })
      break
    case 'file':
      break
    default:
      console.log('未知类型')
  }
}
const delData = async () => {
  const { getSelections } = methods
  const selections = await getSelections()
  const ids = selections.map((v) => v.goods_id)
  delLoading.value = true
  ElMessageBox.confirm(t('common.delMessage'), t('common.delWarning'), {
    confirmButtonText: t('common.delOk'),
    cancelButtonText: t('common.delCancel'),
    type: 'warning'
  })
    .then(async () => {
      let res = await adminCsGoodsBatchDelApi({ ids: ids.join(',') })
        .catch(() => {})
        .finally(() => {
          delLoading.value = false
        })
      if (res) {
        getList()
      }
    })
    .catch(() => {})
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
      <ElButton type="danger" @click="delData()">批量删除</ElButton>
    </div>
    <!-- v-model:pageSize="tableObject.pageSize" -->

    <Table
      v-model:pageSize="datas.pageSize"
      v-model:currentPage="datas.currentPage"
      :columns="allSchemas.tableColumns"
      :data="datas"
      :loading="datas.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton
          v-if="row.state == 1"
          circle
          :icon="iconEdit"
          @click="action('edit', row)"
          title="编辑"
        />
        <ElButton circle :icon="iconSee" @click="action('see', row)" title="查看" />
        <ElButton
          v-if="row.state == 1"
          circle
          :icon="iconDel"
          @click="action('del', row)"
          title="删除"
        />
        <ElButton
          v-if="row.state == 1"
          circle
          :icon="iconFile"
          @click="action('file', row)"
          title="确认归档"
        />
      </template>
    </Table>
  </ContentWrap>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit
      v-if="actionType == 'edit' || actionType == 'add'"
      ref="editRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />
    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
      :id="tableObject.currentRow.id"
    />
    <template #footer>
      <ElButton
        v-if="actionType == 'edit' || actionType == 'add'"
        type="primary"
        :loading="loading"
        @click="save()"
      >
        保存
      </ElButton>
      <ElButton @click="dialogVisible = false">关闭</ElButton>
    </template>
  </Dialog>
</template>
